#!/usr/bin/env bash
vmmark=$(egrep '(vmx|svm)' /proc/cpuinfo|wc -l)
if [ "$vmmark" -gt 0 ]; then
    echo "具备虚拟化，可以安装KVM"
    echo "开始关闭selinux"
    echo "SELINUX=disabled">/etc/sysconfig/selinux # 关闭Selinux 需要重启后生效
    setenforce 0  # 临时关闭selinux
    yum install qemu-kvm libvirt virt-install bridge-utils -y  # 安装kvm虚拟化以及相关工具
    systemctl start libvirtd   # 启动虚拟化
    systemctl enable libvirtd  # 设置卡机启动
    systemctl status libvirtd  # 展示一下状态
    # 默认使用第一张网卡作为KVM的网络配置网卡，所以请务必保证第一张网卡的配置是没有问题的
    firsten=$(ls /sys/class/net|head -1)
    IPADDR=$(cat /etc/sysconfig/network-scripts/ifcfg-$firsten|grep "IPADDR"|awk -F"=" '{print $2}')
    PREFIX=$(cat /etc/sysconfig/network-scripts/ifcfg-$firsten|grep "PREFIX"|awk -F"=" '{print $2}')
    GATEWAY=$(cat /etc/sysconfig/network-scripts/ifcfg-$firsten|grep "GATEWAY"|awk -F"=" '{print $2}')
    cat>/etc/sysconfig/network-scripts/ifcfg-br0<<EOF
BOOTPROTO=static
DEVICE=br0
TYPE=Bridge
NM_CONTROLLED=no
IPADDR=$IPADDR
PREFIX=$PREFIX
GATEWAY=$GATEWAY
DNS1=114.114.114.114
DNS2=8.8.8.8
ZONE=public
ONBOOT=yes
EOF
    cp /etc/sysconfig/network-scripts/ifcfg-$firsten /etc/sysconfig/network-scripts/ifcfg-$firsten.bak
    cat>/etc/sysconfig/network-scripts/ifcfg-$firsten<<EOF
BOOTPROTO=none
DEVICE=$firsten
NM_CONTROLLED=no
ONBOOT=yes
BRIDGE=br0
EOF
systemctl restart network
    echo "成功安装了KVM到你的机器上了，愉快的使用吧！"
else
    echo "不具备虚拟化的CPU条件，无法安装KVM"
fi